package com.grj.park.boot.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.grj.park.boot.domain.R;
import com.grj.park.boot.domain.UserRole;
import com.grj.park.boot.service.UserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user-role")
@Api(tags = "用户角色管理")
@RequiredArgsConstructor
public class UserRoleController {

    private final UserRoleService userRoleService;

    @GetMapping("/list/{userId}")
    @ApiOperation("查询用户角色列表")
    @PreAuthorize("hasAuthority('user-role:list')")
    public R<List<Long>> fetchUserRoleList(@PathVariable Long userId) {
        List<Long> roleIds = userRoleService.list(Wrappers.lambdaQuery(UserRole.class).eq(UserRole::getUserId, userId)).stream().map(UserRole::getRoleId).collect(Collectors.toList());
        return R.ok(roleIds);
    }


    /**
     * 分页查询用户角色列表
     * @param currentPage 当前页码
     * @param pageSize 每页大小
     * @param userRole 查询条件
     * @return 分页结果
     */
    @GetMapping("/page")
    @ApiOperation("分页查询用户角色列表")
    @PreAuthorize("hasAuthority('user-role:page')")
    public R<Page<UserRole>> fetchUserRolePage(
            @RequestParam int currentPage,
            @RequestParam int pageSize,
            @RequestParam String userRole,
            @RequestParam(required = false) List<Date> during
    ) {
        return R.ok(userRoleService.fetchUserRolePage(currentPage, pageSize, JSONUtil.toBean(userRole, UserRole.class), during));
    }

    /**
     * 更新用户角色
     * @param userRoles 用户角色对象
     * @return 更新结果
     */
    @PutMapping
    @ApiOperation("更新用户角色")
//    @PreAuthorize("hasAuthority('user-role:put')")
    public R<Void> putUserRole(@RequestBody @Valid List<UserRole> userRoles) {
        List<Long> putRoleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        List<UserRole> userRoleList = userRoleService.listAll(userRoles);
        List<Long> roleIds = userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        userRoleService.remove(Wrappers.lambdaQuery(UserRole.class).eq(UserRole::getUserId, userRoles.get(0).getUserId()));

        List<Long> bothList = putRoleIds.stream().filter(roleIds::contains).collect(Collectors.toList());
        if(!bothList.isEmpty()){
            userRoleService.updateUserRoles(userRoleList.stream().filter(userRole -> bothList.contains(userRole.getRoleId())).collect(Collectors.toList()));
        }

        List<Long> otherList = putRoleIds.stream().filter(roleId->!roleIds.contains(roleId)).collect(Collectors.toList());

        if(!otherList.isEmpty()){
            List<UserRole> otherUserRoleList = userRoles.stream().filter(userRole -> otherList.contains(userRole.getRoleId())).collect(Collectors.toList());
            userRoleService.saveBatch(otherUserRoleList);
        }
        return R.okMsg("更新用户角色成功");
    }


}

